package thu.sorit.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import thu.sorit.net.Downloader;
import thu.sorit.resolver.Resolver;
import thu.sorit.resolver.SinaResolver;
import thu.sorit.resolver.TudouResolver;
import thu.sorit.resolver.Util;
import thu.sorit.resolver.Video;
import android.graphics.Bitmap;
import android.util.Log;

public class TestThread extends Thread {

	private boolean enabled = true;
	
	private SoritService service;
	
	private String url;
	
	public TestThread(SoritService service, String url) {
		this.service = service;
		this.url = url;
	}
	
	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}
	
	public boolean getEnabled() {
		return enabled;
	}
	
	public void run() {
		Video video = null;
		Resolver rs[] = service.getResolverList();
		Resolver resolver = getResolver(rs, url);
		if (resolver == null) {
			return;
		} else {
			Log.i("peterfff", "Matched resolver!");
			video = resolver.fillVideo(url);
		}
		for (Resolver r : rs) {
			service.getVideoList().addAll(r.search(video.title, video.preview, video.duration, 0.9));
		}
		for (Video v : service.getVideoList()) {
			if (!enabled) {
				break;
			}
			v.rate = Downloader.testSpeed(v.cdn);
		}
		Collections.sort(service.getVideoList(), new Comparator<Video>() {

			@Override
			public int compare(Video vl, Video vr) {
				if (vl.rate > vr.rate) {
					return -1;
				} else if (vl.rate < vr.rate) {
					return 1;
				} else {
					return 0;
				}
			}
			
		});
		Log.i("peterfff", "all done");
	}

	private Resolver getResolver(Resolver resolver[], String url) {
		for (Resolver r : resolver) {
			if (r.owns(url)) {
				return r;
			}
		}
		return null;
	}
	
}
